package com.yc.net.flydove;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Iterator;
import java.util.Vector;

public class FlyDoveServer {
	
	// 线程安全集合
	Vector<Socket> sockets = new Vector<>();
	
	public static void main(String[] args) throws IOException {
		FlyDoveServer server = new FlyDoveServer();
		server.listen();
		
		System.out.println("wait");
		System.in.read();
		System.out.println("continue");
		
		server.send();
	}
	
	// 监听
	public void listen() {
		new Thread(()->{
			try {
				ServerSocket server = new ServerSocket(9876);
				while(true) {
					System.out.println("监听端口: 9876");
					Socket socket = server.accept();
					InetAddress addr = socket.getInetAddress();
					System.out.println("客户端连接成功: "+addr);
					sockets.add(socket);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}).start();
	}
	
	// 发送
	public void send() throws IOException {
		
		for (Iterator<Socket> iterator = sockets.iterator(); iterator.hasNext();) {
			Socket socket = (Socket) iterator.next();
			// 获取文件 : 文本框输入 或 文件选择窗口输入
			String filepath; // 目录 or 文件
			OutputStream out = socket.getOutputStream();
			// 数据输出流
			DataOutputStream dos = new DataOutputStream(out);
			
			// 目录 :  dir:name
			dos.writeUTF("dir:demo");
			System.out.println("发送目录:demo");
			
			// 文件 :  file:name: 流(文件内容)			
			dos.writeUTF("file:a.txt");
			// 传送文件大小
			dos.writeLong(new File("D:\\dev\\gitee\\yc138\\a.txt").length());
			
			System.out.println("发送file:a.txt");
			try(FileInputStream fis = new FileInputStream("D:\\dev\\gitee\\yc138\\a.txt");){
				byte[] bytes = new byte[1024];
				int count;
				while((count = fis.read(bytes))>-1) {
					out.write(bytes,0,count);
				}
			}
			System.out.println("发送file:a.txt 完成");
			
		}
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

}
